import datetime
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import redirect
from django.conf import settings


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """ 如果用户已登录，则request中赋值 """

        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object

        # url白名单，没有登录也可以访问的url
        '''
        1. 获取当前用户访问的url
        2. 检查url是否在白名单中，如果存在，可以访问
            如果不存在， 判断是否已登录
        '''
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return

        # 检查用户是否已登录，已登录继续往后走，未登录返回登录页面
        if not request.tracer:
            return redirect('login')

        # 登录成功之后，访问后台管理时：获取当前用户所拥有的额度
        # 方式一：免费额度在交易记录中存储
        # 获取当前用户ID值最大（最近交易记录）
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        # 用户过期则更换为免费策略
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2,
                                                        price_policy__category=1).first()
        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):
        # request.tracer = Tracer()

        # 判断url是否以manage开头，如果是，则判断项目ID是否为我参与or创建
        if not request.path_info.startswith('/manage/'):
            return
        project_id = kwargs.get('project_id')
        my_project = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if my_project:
            request.tracer.project = my_project
            return
        join_project = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if join_project:
            request.tracer.project = join_project.project
            return

        return redirect('project_list')
